<?php
class User {
	
	public static function isLogged() {
		if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
			if(!isset($_SESSION['user'])) {
				$_SESSION['user']['username'] = User::perso_decrypt ( $_COOKIE['username'] );
				$_SESSION['user']['password'] = User::perso_decrypt ( $_COOKIE['password'] );
				$_SESSION['user']['mailboxes'] = Imap::getMailboxes();
			}
		}
		return isset($_SESSION['user']);
	}
	
	public static function perso_encrypt ($original_data) {
		$length = strlen($original_data);
		$data_to_encrypt = $length.'|'.$original_data;
		// Encrypt the data including its length.
		// Do not save the length unencrypted, as this could be a (minor) security risk
		
		/* Data */
		$key = COOKIESALT;
		$plain_text = $data_to_encrypt;

		/* Open module, and create IV */
		$td = mcrypt_module_open('des', '', 'ecb', '');
		$key = substr($key, 0, mcrypt_enc_get_key_size($td));
		$iv_size = mcrypt_enc_get_iv_size($td);
		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

		/* Initialize encryption handle */
		if (mcrypt_generic_init($td, $key, $iv) != -1) {
			/* Encrypt data */
			$c_t = mcrypt_generic($td, $plain_text);
			/* Clean up */
			mcrypt_generic_deinit($td);
			mcrypt_module_close($td);
			return $c_t;
		}
		return 'error with mcrypt_generic_init';
	}

	public static function perso_decrypt($cypher) {
		// Decrypt the cypher data first
		/* Data */
		$key = COOKIESALT;
		$c_t = $cypher;

		/* Open module, and create IV */
		$td = mcrypt_module_open('des', '', 'ecb', '');
		$key = substr($key, 0, mcrypt_enc_get_key_size($td));
		$iv_size = mcrypt_enc_get_iv_size($td);
		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

		/* Initialize encryption handle */
		if (mcrypt_generic_init($td, $key, $iv) != -1) {
			/* Decrypt data */
			$p_t = mdecrypt_generic($td, $c_t);
			/* Clean up */
			mcrypt_generic_deinit($td);
			mcrypt_module_close($td);
			// Next retrieve the original data
			list ( $length, $padded_data ) = explode ( '|', $p_t, 2 );
			$original_data = substr ( $padded_data, 0, $length );
			
			return $original_data;
		}
		return 'error with mcrypt_generic_init';
	}
}
?>